import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cartItems: [
      { name: '手机', price: 1000, quantity: 1 },
      { name: '电脑', price: 2000, quantity: 1 },
      { name: '键盘', price: 200, quantity: 2 }
    ]
  },
  getters: {
    cartTotal(state) {
      return state.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0);
    }
  },
  mutations: {
    incrementQuantity(state, index) {
      state.cartItems[index].quantity++;
    },
    decrementQuantity(state, index) {
      if (state.cartItems[index].quantity > 1) {
        state.cartItems[index].quantity--;
      }
    }
  },
  actions: {
    increment({ commit }, index) {
      commit('incrementQuantity', index);
    },
    decrement({ commit }, index) {
      commit('decrementQuantity', index);
    }
  }
});